package com.relax.controller;


import com.relax.service.KafkaProducerService;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

@RestController()
@RequestMapping("/kafka")
public class ProducerController {

    @Autowired
    private KafkaProducerService kafkaProducerService;

    private static final DateTimeFormatter FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    @RequestMapping("/send")
    public void send() {

        String json = "普通消息";
        kafkaProducerService.sendMessage("qaxCsa", getMsg());

    }

    private static long length=0;

    @RequestMapping("/send2")
    public void send2() throws InterruptedException {
        int num = 1;

        String msg2 = getMsg2();
        DpScanResponseDTO dpScanResponseDTO = JSON.parseObject(msg2, DpScanResponseDTO.class);
        List<DpScanResponseDTO.Vul> vulListResult = dpScanResponseDTO.getData().getVul();

        List<AssetVulEvent.VulListDTO> vulList = new ArrayList<>();
        for (DpScanResponseDTO.Vul vul : vulListResult) {
            Integer level = transformLevel(vul.getLevel());
            if(true){
                //过滤掉低危和信息
                if (Objects.isNull(level) || level == 3 || level == 4) {
                    continue;
                }
            }
            AssetVulEvent.VulListDTO vulListDTO = new AssetVulEvent.VulListDTO();
            vulListDTO.setVulType(transformVulType(vul.getFirst_type()));// 0:系统漏洞, 2//web漏洞, 1://弱口令
            vulListDTO.setVulName(vul.getVul_name());
            String vulId = vul.getVul_id();
            try {
                vulListDTO.setVulId(Long.parseLong(vulId));
            } catch (Exception e) {
            }
            vulListDTO.setIp(vul.getIp());
            vulListDTO.setVulLevel(transformLevel(vul.getLevel()));
            vulListDTO.setVulCnnvd(judgeLength(vul.getCnnvd(),50));//经过测试发现有些  "cncve": "CVE-1999-0186\nCVE-1999-0254\nCVE-1999-0472\nCVE-1999-0516\nCVE-1999-0517\nCVE-1999-0792\nCVE-2000-0147\nCVE-2001-0380\nCVE-2001-0514\nCVE-2001-1210\nCVE-2002-0109\nCVE-2002-0478\nCVE-2002-1229\nCVE-2004-0311\nCVE-2004-1474\nCVE-2010-1574",
            vulListDTO.setVulCncve(judgeLength(vul.getCncve(),50));




            vulListDTO.setDescription(vul.getVul_desc());
            vulListDTO.setSolution(vul.getVul_solution());
            vulListDTO.setCvss(vul.getCvss_score());
            vulListDTO.setExt1("DipuScan");
            vulList.add(vulListDTO);
        }



        List<List<AssetVulEvent.VulListDTO>> partition = ListUtils.partition(vulList, 500);
        for (int i = 0; i < partition.size(); i++) {
            List<AssetVulEvent.VulListDTO> vulListDTOS = partition.get(i);
            AssetVulEvent assetVulEvent = new AssetVulEvent();
            assetVulEvent.setTaskId(99);
            assetVulEvent.setTaskName("dp-test");
            assetVulEvent.setSource("DP_SCAN");
            assetVulEvent.setReportUrl("DP_SCAN-report-4");
            assetVulEvent.setVulList(vulListDTOS);
            assetVulEvent.setNum(i);
            kafkaProducerService.sendMessage("dipuTopic", JSON.toJSONString(assetVulEvent));
//            Thread.sleep(1000);
            System.out.println("发送批次"+i+"个数是:{}"+vulListDTOS.size());
        }


    }

    private Integer transformLevel(String level) {
        if (StringUtils.isEmpty(level)) {
            return null;
        }
        if (StringUtils.equals(level, "S") || StringUtils.equals(level, "H")) {
            return 1;
        }
        if (StringUtils.equals(level, "M")) {
            return 2;
        }
        if (StringUtils.equals(level, "L")) {
            return 3;
        }
        if (StringUtils.equals(level, "I")) {
            return 4;
        }
        return null;
    }

    private Integer transformVulType(String vulType) {
        if (StringUtils.isEmpty(vulType)) {
            return null;
        }
        if (StringUtils.equals(vulType, "host") || StringUtils.equals(vulType, "ipc")) {
            return 0;
        }
        if (StringUtils.equals(vulType, "web")) {
            return 2;
        }
        if (StringUtils.equals(vulType, "weak")) {
            return 1;
        }
        return null;
    }





    private String getMsg2() {
        String filePath = "/Users/pqs/Desktop/DIS/dp_2.txt";
        try {
            String content = new String(Files.readAllBytes(Paths.get(filePath)));
            return content;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {

        String msgkafka = getMsg();


        JSONObject jsonObject = null;
        try {
            //解析日志事件
            jsonObject = JSON.parseObject(msgkafka, JSONObject.class);
        } catch (Exception e) {

        }

        boolean logFlag = true;
        JSONObject contents = (JSONObject) jsonObject.get("contents");
        String _contentString = contents.getString("_content_");
        JSONObject _content_ = JSON.parseObject(_contentString, JSONObject.class);
        JSONObject fieldValues = (JSONObject) _content_.get("fieldValues");
        System.out.println(fieldValues);



    }

    private String judgeLength(String value, int i) {
        if(StringUtils.isEmpty(value)){
            return null;
        }
        if(value.length() <i){
            return value;
        }
        if(value.contains("\n")){
            int newlineIndex = value.indexOf("\n");
            String substring = value.substring(0, newlineIndex);
            return substring;
        }else {
            return  value.substring(0, i);
        }
    }


    private static String getMsg() {
        LocalDateTime lstarttime = Instant.ofEpochMilli(System.currentTimeMillis())
                .atZone(ZoneId.systemDefault())  // 获取系统默认时区
                .toLocalDateTime();
        String createTime = FORMAT.format(lstarttime);
        System.out.println(createTime);

        String msg = "{\"model\":\"event\",\"fieldValues\":{\"devid\":\"1ac68b5d889d443094a0ee121b038186\",\"lid\":17879296261501733,\"Memory\":4016.0,\"CPU\":4.0,\"cvendor\":\"qax\",\"file_sha256\":\"\",\"cproduct\":\"天擎\",\"number\":428,\"ieventpri\":-999,\"cdevip\":\"38.104.28.36\",\"cusername\":\"YLT\",\"model\":\"event\",\"state\":\"自动阻止\",\"threattype\":\"网络入侵防护\",\"ccolletorip\":\"38.104.24.9\",\"public_date\":1743381992000,\"lstarttime\":1737447930000,\"cdevtype\":\"/security/terminal\",\"cregex\":\"AV_TianQing_2\",\"cprogram\":\"38.105.190.60\",\"OS\":\"WINDOWS\",\"loccurtime\":1743390467000,\"ceventdesc\":\"已成功阻断永恒之蓝(MS17-010)远程漏洞攻击-301\",\"ccollectsource\":\"38.104.28.36:UDP:514\",\"cdealStatus\":\"正常\",\"workstation\":\"WORKGROUP\",\"csip_v6\":\"\",\"corilog\":\"{\\\"client_domain\\\":null,\\\"client_info\\\":{\\\"access_point\\\":{\\\"deployment_id\\\":{\\\"asset_id\\\":{\\\"oid\\\":\\\"2715663413345781025\\\",\\\"id\\\":\\\"2914807011512156306\\\"},\\\"id\\\":\\\"skylar_console_id\\\"},\\\"id\\\":\\\"console.qax-ats-ca.2715663413345781025.t68i-c1i9-8whc-wec8\\\"},\\\"mid\\\":\\\"1ac68b5d889d443094a0ee121b038186\\\",\\\"client_type\\\":\\\"win\\\",\\\"core_number\\\":4,\\\"mac\\\":\\\"00-50-C2-41-3D-DA\\\",\\\"update_time\\\":\\\"2025-03-31T00:46:32Z\\\",\\\"ipv6\\\":\\\"\\\",\\\"ie_version\\\":\\\"8.0.7601.17514\\\",\\\"computer_working_group\\\":\\\"WORKGROUP\\\",\\\"tos\\\":{\\\"desktop\\\":true,\\\"os\\\":1,\\\"dist\\\":\\\"Windows 7 SP1 Ultimate\\\",\\\"arch\\\":2,\\\"version\\\":{\\\"kernel_version\\\":\\\"7601:Service Pack 1\\\",\\\"version\\\":\\\"6.1\\\"}},\\\"os_bit\\\":1,\\\"report_ipv6\\\":\\\"\\\",\\\"state\\\":0,\\\"system_language\\\":\\\"zh-JT\\\",\\\"report_ip\\\":\\\"38.105.88.200\\\",\\\"create_time\\\":\\\"2025-01-21T08:25:30Z\\\",\\\"os\\\":0,\\\"asset_version\\\":{\\\"update_time\\\":\\\"2025-03-27T06:46:01Z\\\",\\\"peripheral_devices_version\\\":\\\"2024.05.09.0920\\\",\\\"create_time\\\":\\\"2025-01-21T08:25:31Z\\\",\\\"software_library_version\\\":\\\"2025.01.13.1732\\\",\\\"virus_bd_version\\\":\\\"0.0.0.0\\\",\\\"delete_at\\\":\\\"1970-01-01T00:00:00Z\\\",\\\"virus_version\\\":\\\"2025.03.25.3001\\\",\\\"patch_version\\\":\\\"2025.03.21.1000\\\",\\\"main_program_version\\\":\\\"10.7.0.2362\\\"},\\\"ip\\\":\\\"38.105.88.200\\\",\\\"os_version\\\":{\\\"release_id\\\":\\\"6.1\\\",\\\"build_version\\\":\\\"7601:Service Pack 1\\\",\\\"main\\\":\\\"Windows 7 SP1\\\",\\\"describe\\\":\\\"Ultimate\\\"},\\\"asset_computer\\\":{\\\"update_time\\\":\\\"2025-03-29T03:45:35Z\\\",\\\"create_time\\\":\\\"2025-01-21T08:25:31Z\\\",\\\"board_serial_number\\\":\\\"NORCO-0123456789\\\",\\\"board_model\\\":\\\"NORCO ATX-6959\\\",\\\"delete_at\\\":\\\"1970-01-01T00:00:00Z\\\",\\\"board_bios\\\":\\\"American Megatrends Inc. 6959I102 :12/30/2015\\\",\\\"brand_model\\\":\\\"To be filled by O.E.M. To be filled by O.E.M.(To be filled by O.E.M.)\\\",\\\"board_chipset\\\":\\\"Intel(R) H81 LPC Controller - 8C5C\\\",\\\"board_temperature\\\":\\\"\\\"},\\\"sys_space\\\":\\\"12086\\\",\\\"login_account\\\":\\\"YLT\\\",\\\"memory_size\\\":4016,\\\"domain\\\":\\\"\\\",\\\"name\\\":\\\"YLT-PC\\\",\\\"nic_list\\\":[],\\\"activation\\\":true,\\\"online_info\\\":{\\\"last_time\\\":\\\"2025-03-31T03:03:19.006960690Z\\\",\\\"is_online\\\":true,\\\"state\\\":0}},\\\"group_info\\\":[{\\\"node_type\\\":0,\\\"tree_id\\\":\\\"50e6f8011a00ea0a\\\",\\\"node_name\\\":\\\"户籍窗口\\\",\\\"oid\\\":\\\"2914807011512156306\\\",\\\"node_id\\\":\\\"50e7fdb47e00ea19\\\"}],\\\"client_activation\\\":\\\"1\\\",\\\"defend_action\\\":3,\\\"client_core_number\\\":\\\"4\\\",\\\"user_mobile_phone_number\\\":null,\\\"user_source_factor\\\":null,\\\"user_mobile_phone_country_code\\\":null,\\\"group_node_type\\\":\\\"0\\\",\\\"client_os_bit\\\":\\\"1\\\",\\\"asset_id\\\":2914807011512156306,\\\"client_type\\\":\\\"win\\\",\\\"sync_time\\\":1743390470,\\\"client_id\\\":\\\"4825351-8c04f31bbbeac1f8b8af7c657e91a630\\\",\\\"asset_oid\\\":2715663413345781025,\\\"client_tos_dist\\\":\\\"Windows 7 SP1 Ultimate\\\",\\\"client_state\\\":\\\"0\\\",\\\"user_info\\\":null,\\\"client_login_account\\\":\\\"YLT\\\",\\\"client_tos_os\\\":1,\\\"action\\\":21,\\\"client_create_time\\\":\\\"2025-01-21T08:25:30Z\\\",\\\"client_ip\\\":\\\"38.105.88.200\\\",\\\"group_node_path\\\":\\\"\\\",\\\"user_source_factor_id\\\":null,\\\"client_os_version_main\\\":\\\"Windows 7 SP1\\\",\\\"user_email\\\":null,\\\"create_time\\\":1743390467,\\\"client_os_version_describe\\\":\\\"Ultimate\\\",\\\"client_os_version_build_version\\\":\\\"7601:Service Pack 1\\\",\\\"trigger_mode\\\":11,\\\"user_create_time\\\":null,\\\"client_memory_size\\\":\\\"4016\\\",\\\"group_oid\\\":\\\"2914807011512156306\\\",\\\"user_user_name\\\":null,\\\"group_node_id\\\":\\\"50e7fdb54e00ea19\\\",\\\"client_ie_version\\\":\\\"8.0.7601.17514\\\",\\\"risk_file\\\":null,\\\"sha1\\\":null,\\\"client_tos_version\\\":\\\"6.1\\\",\\\"login_user\\\":null,\\\"user_id\\\":null,\\\"user_real_name\\\":null,\\\"client_sys_space\\\":\\\"12086\\\",\\\"subject_process\\\":\\\"38.105.190.60\\\",\\\"collect_time\\\":1743390470094,\\\"group_tree_id\\\":\\\"50e6f8011a00ea0a\\\",\\\"object\\\":\\\"38.105.88.200\\\",\\\"event_count\\\":428,\\\"client_report_ipv6\\\":null,\\\"client_computer_working_group\\\":\\\"WORKGROUP\\\",\\\"user_state\\\":null,\\\"user_third_id\\\":null,\\\"client_nic_list\\\":\\\"[]\\\",\\\"client_report_ip\\\":\\\"38.105.88.200\\\",\\\"client_os\\\":\\\"0\\\",\\\"region_name\\\":null,\\\"user_source_factor_name\\\":null,\\\"client_name\\\":\\\"YLT-PC\\\",\\\"user_update_time\\\":null,\\\"auth_node_id\\\":\\\"2914809725646334474,50e7fdb45e00ea19,50e7fdb47e00ea19,50e7fdb54e00ea19\\\",\\\"client_mac\\\":\\\"00-50-C2-41-3D-DA\\\",\\\"client_tos_arch\\\":2,\\\"user_group_info\\\":null,\\\"client_system_language\\\":\\\"zh-JT\\\",\\\"client_update_time\\\":\\\"2025-03-31T00:46:32Z\\\",\\\"risk_detail\\\":\\\"已成功阻断永恒之蓝(MS17-010)远程漏洞攻击-301\\\",\\\"client_mid\\\":\\\"1ac68b5d889d443094a0ee121b038186\\\",\\\"search_id\\\":\\\"2715663413345781025_2914807011512156306_50e6f8011a00ea0a_2914809725646334474_50e7fdb45e00ea19_50e7fdb47e00ea19_50e7fdb54e00ea19\\\",\\\"client_os_version_release_id\\\":\\\"6.1\\\",\\\"group_node_name\\\":\\\"户籍窗口\\\",\\\"user_group_names\\\":null,\\\"event_time\\\":1743390709000000000,\\\"user_group_id\\\":null,\\\"syslog_topic\\\":\\\"system_protection_log\\\",\\\"md5\\\":null}\",\"cprogram_path\":\"38.105.88.200\",\"cschema\":\"allAttrs\",\"lreceipttime\":1743390663230,\"chost\":\"YLT-PC\",\"ciaddr\":\"38.105.88.200\",\"groupName\":\"[\\\"全网终端\\\",\\\"PC\\\",\\\"静安寺所\\\",\\\"户籍窗口\\\"]\",\"ceventname\":\"网络访问\",\"coritype\":\"系统防护日志\",\"cobject_file\":\"\",\"csmac\":\"00-50-C2-41-3D-DA\",\"domain\":\"\",\"clogtype\":\"/orilog\",\"creportip\":\"38.105.88.200\",\"MD5\":\"\"},\"sid\":\"17879296261501733\"}";
        Map _contentMap = new HashMap<>();
        _contentMap.put("_client_ip_", "172.20.54.34");
        _contentMap.put("_content_", msg);

        Map map = new HashMap<>();
        map.put("contents", _contentMap);
        map.put("time", 1723187676);


        String msgkafka = JSON.toJSONString(map);
        return msgkafka;
    }
}
